package com.juhe.transmission.servlet.view;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拷贝文件到 document
 * @author liuxin
 *
 */
public class CopyServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");

		String sourceFileName = req.getParameter("file");
		System.out.println(sourceFileName);
		File file = new File(sourceFileName);
		boolean isFile = file.isFile();
		
		if(isFile){
			String fileName = sourceFileName.substring(sourceFileName.lastIndexOf("\\"),sourceFileName.length());
			String destFileName = req.getSession().getServletContext().getRealPath("/") + "document" + fileName;
			copy(sourceFileName, destFileName);//将文件拷贝到document目录中
			req.setAttribute("file", fileName);
			req.getRequestDispatcher("download.jsp").forward(req, resp);
			
		} else {
			req.setAttribute("file", file.getPath());
			req.getRequestDispatcher("readFile.do").forward(req, resp);
		}
		
	}


	/**
	 * 复制文件
	 * @sourceFileName 源文件名
	 * @destFileName 目标文件名
	 */
	public static void copy(String sourceFileName, String destFileName){
		
		BufferedInputStream in = null;
		BufferedOutputStream out = null;
		
		try{
			in = new BufferedInputStream(new FileInputStream(new File(sourceFileName)));			
			out = new BufferedOutputStream(new FileOutputStream(new File(destFileName)));
			
			byte[] buffer = new byte[1024];
			
			int readCount = -1;
			
			while((readCount = in.read(buffer, 0, buffer.length)) != -1){				
				out.write(buffer, 0, readCount);
			}
			out.flush();
			
		}catch(Exception ex){
			ex.printStackTrace();	
		}finally{
			try{
				if(out != null){
					out.close();
				}
				if(in != null){
					in.close();
				}
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
		
	}
	
}
